<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

class Privatesea extends Backend
{
    // 设置关联查询
    protected $relationSearch = true;

    // 当前模型
    protected $model = null;

    // 无需登陆
    protected $noNeedLogin = [];
    // 无需鉴权
    protected $noNeedRight = [];

    protected $RegionModel = NULL;

    public function __construct(){
        parent::__construct();

        $this->model = model('Business.User');
        $this->SourceModel = model('Business.Source');
        $this->AdminModel = model('Admin');
        $this->ReceiveModel = model('Business.Receive');
        $this->RegionModel = model('Region');
        $SexList = [
            0 => '保密',
            1 => '男',
            2 => '女'
        ];

        $DealList = [
            0 => '未成交',
            1 => '已成交'
        ];

        $SourceList = $this->SourceModel->column('id,name');

        $this->assign([
            'SexList' => $SexList,
            'DealList' => $DealList,
            'SourceList' => $SourceList
        ]);
    }

    public function index(){
        // 接收请求，查询数据
        // 判断是否有ajax请求
        //将请求当中所有的参数去除html标签，去掉两边空白
        $this->request->filter(['strip_tags', 'trim']);

        if($this->request->isAjax()){
            //获取表格所提交过来筛选和排序的一些参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 表格需要两个返回值参数 总条数和分页的数据
            $total = $this->model
                ->with(['source'])
                ->where($where)
                ->where('adminid',$this->auth->id)
                ->order($sort,$order)
                ->count(); //返回查询的总数

            // var_dump($total);
            // exit;
            $list = $this->model
                ->with(['source'])
                ->where($where)
                ->where('adminid',$this->auth->id)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();
            // var_dump(collection($list)->toArray());
            // exit;

            // 打印sql语句
            // echo $this->model->getLastSql();
            // exit;

            // 组装数据
            $result = [
                'total' => $total,
                'rows' => $list
            ];
            // 返回给ajax的数据
            return json($result);  

        }
        return $this->view->fetch();
    }

    public function add(){
        // 接收post请求
        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            // var_dump($params);
            // exit;

            // 组装数据
            $data = [
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
                'gender' => $params['gender'],
                'deal' => $params['deal'],
                'sourceid' => $params['sourceid']
            ];
            $data['auth'] = 0;
            $password = $params['mobile'];
            $salt = randstr();
            $password = md5($password.$salt);

            $data['password'] = $password;
            $data['salt'] = $salt;
            $data['money'] = 0;
            $data['adminid'] = $this->auth->id;
            // 选择地区
            if(!empty($params['code'])){
                $parentpath = $this->RegionModel->where('code',$params['code'])->value('parentpath');

                if(!$parentpath){
                    $this->error('该地区不存在，请重新选择');
                }

                $path = explode(',',$parentpath);
                $province = $path[0] ?? null;
                $city = $path[1] ?? null;
                $district = $path[2] ?? null;

                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }

            // var_dump($data);
            // exit;

            // 开启事务
            $this->model->startTrans();
            $this->ReceiveModel->startTrans();

            $BusinessStatus = $this->model->validate('common/Business/Business')->save($data);

            if($BusinessStatus === FALSE){
                $this->error($this->model->getError());
            }
            // var_dump($this->auth->id);
            // exit;
            // 封装申请表
            $ReceiveData = [
                'applyid' => $this->auth->id,
                'status' => 'apply',
                'busid' => $this->model->id
            ];
            
            // var_dump($ReceiveData);
            // exit;
            $ReceiveStatus = $this->ReceiveModel->validate('common/Business/Receive')->save($ReceiveData);

            if($ReceiveStatus === FALSE){
                $this->model->rollback();
                $this->error($this->ReceiveModel->getError());
            
            }

            if($BusinessStatus === FALSE || $ReceiveStatus === FALSE){
                $this->model->rollback();
                $this->ReceiveModel->rollback();
                $this->error('添加客户失败');
                exit;
            }else{
                $this->model->commit();
                $this->ReceiveModel->commit();
                $this->success('添加客户成功');
                exit;
            }

        }
        
        return $this->view->fetch();
    }

    public function edit($ids=NULL){
        $row = $this->model->find($ids);
        // var_dump($row);
        // exit;

        // 没有数据
        if(!$row){
            $this->error(__('No Results were found'));
            exit;
        }

        // 接收post请求
        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            // var_dump($params);
            // exit;

            // 组装数据
            $data = [
                'id' => $ids,
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
                'gender' => $params['gender'],
                'deal' => $params['deal'],
                'sourceid' => $params['sourceid']
            ];

            if($data['email'] != $params['email']){
                $data['auth'] = 0;
            }

            if(!empty($params['password'])){
                $salt = randstr();
                $data['password'] = md5($params['password'].$salt);
                $data['salt'] = $salt;
            }

            // 选择地区
            if(!empty($params['code'])){
                $parentpath = $this->RegionModel->where('code',$params['code'])->value('parentpath');

                if(!$parentpath){
                    $this->error('该地区不存在，请重新选择');
                }

                $path = explode(',',$parentpath);
                $province = $path[0] ?? null;
                $city = $path[1] ?? null;
                $district = $path[2] ?? null;

                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }

            // var_dump($data);
            // exit;

            $result = $this->model->validate('common/Business/Business')->isUpdate(true)->save($data);

            if($result === FALSE){
                $this->error($this->model->getError());
                exit;
            }else{
                $this->success('编辑客户成功');
                exit;
            }

        }

        // 处理地区数据回显
        $row['regionCode'] = $row['district'] ?: ($row['city'] ?: $row['province']);

        $this->assign([
            "row" => $row
        ]);
        
        return $this->view->fetch();
    }

    public function del($ids=NULL){
        $list = $this->model->select($ids);
        // var_dump($list);
        // exit;

        // 没有数据
        if(!$list){
            $this->error(__('No Results were found'));
            exit;
        }

        // 软删除
        $result = $this->model->destroy($ids);
        
        if($result === FALSE){
            $this->error("删除失败");
            exit;
        }else{
            $this->success("删除成功");
            exit;
        }
    }

    public function recycle($ids=NULL){
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->model->column('id');

        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__('No Results were found'));
                exit;
            }
        }

        $businessData = [];
        $ReceiveData = [];

        foreach($ids as $value){
            $ReceiveStatus[] = [
                'applyid' => NULL,
                'status' => 'recovery',
                'busid' => $value
            ];

            $businessData[] = [
                'id' => $value,
                'adminid' => null
            ];
        }

        // 开启事务
        $this->model->startTrans();
        $this->ReceiveModel->startTrans();


        // 更新用户表
        $BusinessStatus = $this->model->saveAll($businessData);
        if($BusinessStatus === FALSE){
            $this->error($this->model->getError());
        }

        // 跟新领取表
        $ReceiveStatus = $this->ReceiveModel->saveAll($ReceiveData);
        if($ReceiveStatus === FALSE){
            $this->model->rollback();
            $this->error($this->ReceiveModel->getError());
        }

        if($BusinessStatus === FALSE || $ReceiveStatus === FALSE){
            $this->model->rollback();
            $this->ReceiveModel->rollback();
            $this->error('回收失败');
            exit;
        }else{
            $this->model->commit();
            $this->ReceiveModel->commit();
            $this->success('回收成功');
            exit;
        }

    }

}
